<template>
  <div>
    <bread :second="'商品管理'" :third="'商品列表'"></bread>
    <el-card class="box-card" style="margin-top:15px ">
      <!-- 添加分类按钮 -->
      <el-col style="margin-bottom:15px">
        <el-row>
          <el-button type="primary" @click="addCates()">添加分类</el-button>
        </el-row>
      </el-col>
      <!-------------------------------- 表格区域   tree插件------------------------------------>
      <zk-table
        ref="table"
        sum-text="sum"
        index-text="#"
        :data="cateList"
        :columns="columns"
        :stripe="props.stripe"
        :border="props.border"
        :show-header="props.showHeader"
        :show-summary="props.showSummary"
        :show-row-hover="props.showRowHover"
        :show-index="props.showIndex"
        :tree-type="props.treeType"
        :is-fold="props.isFold"
        :expand-type="props.expandType"
        :selection-type="props.selectionType"
      >
        <!-- 原文中 scope="scope" 会警告， 2.5版本后应为slot-scope="scope"-->
        <template slot="active" slot-scope="scope">
          <!--  ... ... (图中对应状态栏的绿点儿)-->
          <!-- {{scope.row.cat_deleted}} -->
          <span v-if="scope.row.cat_deleted" class="el-icon-error"></span>
          <span v-else class="el-icon-success" style="color:green"></span>
        </template>

        <template slot="empower" slot-scope="scope">
          <!-- ... ... (为授权的图标，可在这里添加点击事件)-->
          <el-tag v-if="scope.row.cat_level==0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level==1">二级</el-tag>
          <el-tag type="info" v-else>三级</el-tag>
        </template>

        <template slot="id" slot-scope="scope">
          <!-- ... ... (为授权的图标，可在这里添加点击事件)-->
          id={{scope.row.cat_id}}
          <el-button type="warning" size="mini">编辑</el-button>
          <el-button type="danger" size="mini" @click="deleteCate(scope.row)">删除</el-button>
        </template>
      </zk-table>

      <!---------------------------------- 分页区域 --------------------------------------->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!------------------------- 添加分类弹出框（级联选择器） ------------------------------->
    <el-dialog title="添加分类" :visible.sync="cateDialogFormVisible">
      <el-form :model="cateForm" :rules="rulesFrom" ref="cateFormDialog">
        <el-form-item label="分类名称" prop="cat_name" :label-width="formLabelWidth">
          <el-input v-model="cateForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <!------------------------- 级联选择器 ---------------------------->
        <el-form-item label="父级分类" :label-width="formLabelWidth">
          <div class="block">
            <el-cascader
              v-model="value"
              :options="cateCasList"
              :props="props2"
              @change="handleChange"
              clearable
              change-on-select
            ></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cateDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
           
<script>
import { getCategories_api, addCategories_api } from "@/api/login_api.js";
import {deleteCategories_api} from "@/api/index.js";
export default {
  data() {
    return {
      formLabelWidth: "120px",
      //定义一个空数组，默认获取商品分类列表
      cateList: [],
      //设置查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      props: {
        stripe: false, //是否显示间隔斑马纹
        border: true, //是否显示纵向边框
        showHeader: true, //是否显示表头
        showSummary: false, //是否显示表尾合计行
        showRowHover: true, //鼠标悬停时，是否高亮当前行
        showIndex: true, //是否显示数据索引
        treeType: true, //是否为树形表格
        isFold: true, //树形表格中父级是否默认折叠
        expandType: false, //是否为展开行类型表格（为 True 时，需要添加作用域插槽, 它可以获取到 row, rowIndex)
        selectionType: false //是否显示间隔斑马纹
      },
      //表格标题数据-------------------------------------
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          prop: "active",
          type: "template",
          template: "active"
        },
        {
          label: "排序",
          prop: "empower",
          type: "template",
          template: "empower"
        },
        {
          label: "操作",
          prop: "id",
          type: "template",
          template: "id"
        }
      ],
      //添加分类弹窗------------------------------
      cateDialogFormVisible: false,
      rulesFrom: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      //级联选择器---------------
      value: [],
      cateCasList: [],
      cateForm: { cat_name: "", cat_pid: "", cat_level: "" },
      props2: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      }
    };
  },
  //渲染页面-----------------------------------------------
  created() {
    this.getCateList();
  },
  methods: {
    //发送sxios请求，获取商品类表数据---------------------------
    async getCateList() {
      const { data: res } = await getCategories_api(this.queryInfo);
      // console.log(res, 33333);
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败！");
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    //分页功能---------------------------------------------
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getCateList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getCateList();
    },
    //添加商品分类-----------------------------------------------
    async addCates() {
      this.cateDialogFormVisible = true;
      const { data: res } = await getCategories_api({ type: 2 });
      // console.log(res.data, 4444);
      this.cateCasList = res.data;
    },
    //级联选择器功能-----------------------------------------
    handleChange() {},
    //点击弹窗的确认按钮完成分类添加---------------------------
    addCateBtn() {
      //点击确认做二次校验
      this.$refs.cateFormDialog.validate(async valid => {
        if (valid) {
          /*cateForm: { cat_name: "", cat_pid: "", cat_level: "" }
          发送axios请求需要以上三个参数
          cat_id 取级联里面数组里的最后一项
          */
          console.log(this.value, 555555);
          //判断数组的长度，如果长度>0,this.length-1,如果等于0，this.length=0
          if (this.value.length > 0) {
            this.cateForm.cat_pid = this.value[this.value.length - 1];
          } else {
            this.cateForm.cat_pid = 0;
          }
          //cat_level 值为 “0，1，2” 分别和数组的索引【0，1，2】对应
          this.cateForm.cat_level = this.value.length;
          //3个参数凑齐了，可以发送axios请求
          const { data: res } = await addCategories_api(this.cateForm);
          console.log(res, 77777777);
          //最后关闭弹窗，刷新页面，清空form,关闭验证
          this.cateDialogFormVisible = false;
          //  this.$refs.formDialogAddCate.resetFields()
          this.getCateList();
          this.value = [];
          this.cateForm = { cat_name: "", cat_pid: "", cat_level: "" };
        } else {
          this.$message.error("分类添加失败");
          return false;
        }
      });
    },
    //删除商品分类--------------------------
   async deleteCate(row) {
     console.log(row,2222);
    const res =await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
        if(res=='confirm') {
          const {data:res}=await deleteCategories_api(row);
          console.log(res,555);
          this.getCateList();
        }
    }
  }
};
</script>
<style scoped>
</style>